/**
 * 
 */
package com.trendytech.tds.system.dao.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Repository;

import com.trendytech.tds.entity.User;
import com.trendytech.tds.system.dao.IUserDAO;

import hm.base.dao.impl.AbstractDAO;

/**
 * @author Robin
 *
 */
@Repository
public class UserDAOImpl extends AbstractDAO<User> implements IUserDAO {

	public static final String MAPPER_SELECT_BY_USERNAME = "selectByUsername";
	public static final String MAPPER_INSERT_USER_ROLE = "insertUserRole";
	public static final String MAPPER_DELETE_USER_ROLE = "deleteUserRole";
	public static final String MAPPER_SELECT_BY_ROLEID ="selectByRoleId";
	public static final String MAPPER_DELETE_USERS_IN_ROLE = "deleteUsersInRole";
	public static final String MAPPER_SELECT_USERS_NAME_BY_ID = "selectByUserIdForName";
	@Override
	public User getByUsername(String username) {
		List<User> users = sqlSession.selectList(
				getMapperId(MAPPER_SELECT_BY_USERNAME), username);
		if (users != null && !users.isEmpty()) {
			return users.get(0);
		}
		return null;
	}

	@Override
	public int insertUserRole(String userId, String roleId) {
		Map<String, String> userRoleMap = new HashMap<String, String>();
		userRoleMap.put("userId", userId);
		userRoleMap.put("roleId", roleId);
		return sqlSession.insert(getMapperId(MAPPER_INSERT_USER_ROLE), userRoleMap);
	}
	
	@Override
	public int deleteUserRole(String userId, String roleId){
		Map<String, String> userRoleMap = new HashMap<String, String>();
		userRoleMap.put("userId", userId);
		userRoleMap.put("roleId", roleId);
		return sqlSession.delete(getMapperId(MAPPER_DELETE_USER_ROLE), userRoleMap);
	}
	
	@Override
	public int deleteUsersInRole(String userId){
		Map<String, String> userMap = new HashMap<String, String>();
		userMap.put("userId", userId);
		return sqlSession.delete(getMapperId(MAPPER_DELETE_USERS_IN_ROLE), userMap);
	}
	
	@Override
	public List<User> selectByRoleId(String roleId) {
		List<User> users = sqlSession.selectList(
				getMapperId(MAPPER_SELECT_BY_ROLEID), roleId);
		if (users != null && !users.isEmpty()) {
			return users;
		}
		return null;
	}

	@Override
	public String getNameById(String userId) {
		Map<String, String> userMap = new HashMap<String, String>();
		userMap.put("id", userId);
		return sqlSession.selectOne(getMapperId(MAPPER_SELECT_USERS_NAME_BY_ID), userMap);
	}
}
